<?php

namespace backend\controllers;

use app\components\Aliyunoss;
use backend\components\Qiniu;
use backend\models\Brand;
use backend\models\EveryIsOk;
use yii\data\Pagination;
use yii\web\Controller;
use xj\uploadify\UploadAction;
//use crazyfd\qiniu\Qiniu;


class BrandController extends Controller
{

    /**
     * 添加行为控制过滤
     * @return array
     */
    public function behaviors()
    {
        return [
            'access'=>[
                'class'=>'backend\filter\AccessFilter',
            ],
        ];
    }
    /*
     * 进度条
     */
    public function actions() {
        return [
            's-upload' => [
                'class' => UploadAction::className(),
                'basePath' => '@webroot/uploads',
                'baseUrl' => '@web/uploads',
                'enableCsrf' => true, // default
                'postFieldName' => 'Filedata', // default
                //BEGIN METHOD
                //'format' => [$this, 'methodName'],
                //END METHOD
                //BEGIN CLOSURE BY-HASH
                'overwriteIfExist' => true,
                /*'format' => function (UploadAction $action) {
                    $fileext = $action->uploadfile->getExtension();
                    $filename = sha1_file($action->uploadfile->tempName);
                    return "{$filename}.{$fileext}";
                },*/
                //END CLOSURE BY-HASH
                //BEGIN CLOSURE BY TIME
                'format' => function (UploadAction $action) {
                    $fileext = $action->uploadfile->getExtension();
                    $filehash = sha1(uniqid() . time());
                    $p1 = substr($filehash, 0, 2);
                    $p2 = substr($filehash, 2, 2);
                    return "{$p1}/{$p2}/{$filehash}.{$fileext}";
                },
                //END CLOSURE BY TIME
                'validateOptions' => [
                    'extensions' => ['jpg', 'png'],
                    'maxSize' => 1 * 1024 * 1024, //file size
                ],
                'beforeValidate' => function (UploadAction $action) {
                    //throw new Exception('test error');
                },
                'afterValidate' => function (UploadAction $action) {},
                'beforeSave' => function (UploadAction $action) {},
                'afterSave' => function (UploadAction $action) {
                    $action->output['fileUrl'] = $action->getWebUrl();
                    $action->getFilename(); // "image/yyyymmddtimerand.jpg"
                    $action->getWebUrl(); //  "baseUrl + filename, /upload/image/yyyymmddtimerand.jpg"
                    $action->getSavePath(); // "/var/www/htdocs/upload/image/yyyymmddtimerand.jpg"
                },
            ],
        ];
    }


    /**
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }
    /*
     *     显示商品的品牌的列表
     * 1 获取所需的数据
     *      a 实现分页的功能
     * 2 显示视图
     */
    public function actionList(){
        //获得活动记录的对象的数组
        //$model = Brand::find()->where(['!=','status','-1'])->all();
        $query = Brand::find()->where(['!=','status','-1']);
        //获取数据的总的条数
        $counts = $query->count();
        $pagesize = 3;
        //通过该分页工具实现分页的功能
        $pager = new Pagination(['pageSize'=>$pagesize,'totalCount'=>$counts]);
        //获取数据
        $models = $query->limit($pager->limit)->offset($pager->offset)->all();

        //显示视图
        return $this->render('list',['models'=>$models,'pager'=>$pager]);

    }
    /*
     *  实现商品品牌的添加
     */
    public function actionAdd(){
        //实例化表单模型
        $model = new Brand();

        //实例化请求对象
        $request = \Yii::$app->request;
        //加载数据
        if($request->isPost && $model->load($request->post())){
            //保存文件上传的对象
            //$model->imginfo = UploadedFile::getInstance($model,'imginfo');
            //验证数据
            //获取上传的图片的绝对路径
            $absolutePath = \Yii::getAlias('@webroot').$model->logo;
            //实例化对象
            /** @var Qiniu $qiniu */
            $qiniu = \Yii::$app->get('qiniu');
            //上传图像
            $qiniu->uploadFile($absolutePath,$model->logo);
            //获取图像的外链
            $url = $qiniu->getLink($model->logo);
            //保存外链作为图像的地址
            $model->logo = $url;
            //验证并且保存数据
            if($model->validate() && $model->save()){
                //保存数据后跳转到之前的页面
                return $this->redirect(['brand/list']);
            }
        }
        //显示添加品牌的视图
        return $this->render('add',['model'=>$model]);
    }


    /*
     * 实现删除品牌的功能 (把状态标记为删除)
     */
    public function actionDel($id){
        //把商品的状态标记为-1
        $rs = Brand::findOne(['id'=>$id]);
        \Yii::$app->db->createCommand()
            ->update('brand',['status'=>-1],['id'=>$id])
        ->query();
        //删除成功后给与提示
        EveryIsOk::setTisiInfo($rs,'删除');
        //跳转到列表页面
        return $this->redirect(['brand/list']);
    }
    /*
     * 恢复删除的数据
     */
    public function actionRecovery($id){
        //把商品的状态标记为1
        $rs = Brand::findOne(['id'=>$id]);
        \Yii::$app->db->createCommand()
            ->update('brand',['status'=>1],['id'=>$id])
            ->query();
        //恢复成功后给与提示
        if($rs){
            \Yii::$app->session->setFlash('warning','恢复成功!');
        }else{
            //var_dump($rs);exit;
        }
        //跳转到列表页面
        return $this->redirect(['brand/list']);
    }

    /*
     *  实现品牌的编辑修改
     */
    public function actionEdit($id){
        //实例化表单模型
        $model = Brand::findOne(['id'=>$id]);
        //实例化请求对象
        $request = \Yii::$app->request;
        if($request->isPost){
            //加载数据
            $model->load($request->post());
            //验证数据
            if($model->validate()){
                    //验证成功后保存数据
                    $model->save();
                    //保存数据后跳转到之前的页面
                    return $this->redirect(['brand/list']);
            }
        }

        //显示添加品牌的视图
        return $this->render('add',['model'=>$model]);
    }

    /*
     * 显示回收站 (已经删除的商品品牌的列表)
     */
    public function actionRecycleBin(){
        //获得活动记录的对象的数组
        //$models = Brand::find()->where(['=','status','-1'])->all();

        $query = Brand::find()->where(['=','status','-1']);
        //获取数据的总的条数
        $counts = $query->count();
        $pagesize = 3;
        //通过该分页工具实现分页的功能
        $pager = new Pagination(['pageSize'=>$pagesize,'totalCount'=>$counts]);
        //获取数据
        $models = $query->limit($pager->limit)->offset($pager->offset)->all();
        //显示视图
        return $this->render('recycleBin',['models'=>$models,'pager'=>$pager]);
    }
    /*
     * 实现品牌的彻底删除
     */
    public function actionDelete($id){
        $rs = \Yii::$app->db->createCommand()->delete('brand',['id'=>$id])->execute();

        if($rs){
            \Yii::$app->session->setFlash('success','彻底删除成功!');
        }else{
            \Yii::$app->session->setFlash('success','彻底删除失败!');
        }

        return $this->redirect(['brand/recycle-bin']);

    }

    /*
     * 展示商标的所有的信息
     *
     */
    public function actionShow($id)
    {
        //实例化表单模型
        $model = Brand::findOne(['id'=>$id]);

        //显示添加品牌的视图
        return $this->render('show',['model'=>$model]);
    }

    public function actionQiniu(){
        /*$ak = '42thf3u3TiA_0eomS_nMKMLmZYhUNNSD4VoOJWOy';

        $sk = 'owzDaJUdJDIGcTbYmEbkJZ4oSCHrWouQer2T2skU';

        $domain = 'http://onkanhlov.bkt.clouddn.com/';

        $bucket = 'yii2-shop';

        $qiniu = new Qiniu($ak, $sk,$domain, $bucket);

        $key = time();
        $filePath= 'F:\server\www\kaosi.cn\Yii2\yii2_git\backend\web\uploads\4b\a6\4ba60b2b37d51fc2c2ebb11615ef0b2585a004f8.jpg';

        $qiniu->uploadFile($filePath,$key);

        $url = $qiniu->getLink($key);

        return $url;*/

        $filePath= 'F:\server\www\kaosi.cn\Yii2\yii2_git\backend\web\uploads\4b\a6\4ba60b2b37d51fc2c2ebb11615ef0b2585a004f8.jpg';

        // $qiniu = new Qiniu();

        /** @var Qiniu $qiniu */
        $qiniu = \Yii::$app->get('Qiniu.class');

        $qiniu->uploadFile($filePath);
        var_dump($qiniu);

    }
    /*
     *测试阿里云
     */
    public function actionAliyun(){
        \Yii::$app->Aliyunoss->test();

        var_dump(new Aliyunoss());

    }

}
